package com.cuit.qx.controller;

import com.cuit.qx.aop.OperLog;
import com.cuit.qx.bean.PageList;
import com.cuit.qx.bean.RoleGroup;
import com.cuit.qx.utils.exception.ServiceException;
import com.cuit.qx.utils.tools.StringUtils;
import com.cuit.qx.bean.User;
import com.cuit.qx.service.MenuInfoService;
import com.cuit.qx.service.RoleManagerService;
import com.cuit.qx.service.UserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping(value = "/api/UserInfoAction")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RoleManagerService roleManagerService;
    @Autowired
    private MenuInfoService menuSerivce;

    private static final Logger LOG = LoggerFactory.getLogger(UserInfoController.class);

    /**
     * 登录
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public Map<String, Object> login(HttpServletRequest request, @RequestBody User user) {
        String loginName = user.getUsername();
        String loginPassword = user.getPassword();
        LOG.info("用户正在登陆" + loginName + "........");
        User userInfo = userInfoService.login(loginName, loginPassword);
        Long count = userInfoService.getUserErrorCount(loginName);
        Map<String, Object> baseMap = new HashMap<String, Object>();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        baseMap.put("token", false);
        if (count == null) {
            resultMap.put("code", 20001);
            baseMap.put("msg", "账号或者密码错误!");
            resultMap.put("data", baseMap);
            return resultMap;
        }
        Date lockDate = userInfoService.getLockDate(loginName);
        if (null == userInfo) {
            //记录账号错误次数
            if (count == 5) {
                //修改最后锁定时间并且修改用户状态
                userInfoService.updateUserCountAndLockDate(loginName, new Date());
                baseMap.put("msg", "失败超过5次，请10分钟后再登陆!");
            } else {
                userInfoService.updateUserErrorCount(loginName, 1);
            }
            resultMap.put("code", 20001);
            baseMap.put("msg", "账号或者密码错误!");
            resultMap.put("data", baseMap);
            return resultMap;
        }
        if (null != lockDate) {
            long errorTime = new Date().getTime() - lockDate.getTime();
            if (errorTime < 10 * 60 * 1000) {
                resultMap.put("code", 20001);
                baseMap.put("msg", "失败超过5次，请10分钟后再登陆!");
                resultMap.put("data", baseMap);
                return resultMap;
            } else {
                //正确后更新用户状态和时间
                userInfoService.updateUserCountAndLockDate(loginName, null);
            }
        }
        if (0 != count) {
            userInfoService.updateUserErrorCount(loginName, 0);
        }
        if (userInfo != null && userInfo.getStatus() == 1) {
            resultMap.put("code", 20001);
            baseMap.put("msg", "账号已经禁用，请联系管理员!");
            resultMap.put("data", baseMap);
            return resultMap;
        }
        //查询用户角色状态
//		String roleId = userInfo.getRole().getGroupid();
//		if(roleInfoService.queryRoleBeanInfo(roleId).getStatus() == 1){
//			throw new ServiceException("角色已禁用，请联系管理员");
//		}
        HttpSession session = request.getSession();
        session.setAttribute("user", userInfo);
        session.setMaxInactiveInterval(-1);

        RoleGroup queryRoleBeanInfo = roleManagerService.queryRoleBeanInfo(userInfo.getGroupId());
        resultMap.put("code", 20000);
        String str = queryRoleBeanInfo.getGroupName() + "-token";
        baseMap.put("token", str);
        baseMap.put("username", userInfo.getUsername());
        resultMap.put("data", baseMap);
        LOG.info(loginName + "登录成功");
        return resultMap;
    }

    @RequestMapping(value = "/loginSuccess")
    @OperLog(operModul = "用户管理", operType = "7", operDesc = "登录")
    @ResponseBody
    public Map<String, Object> userSuccess(HttpServletRequest request, String username) {
        User userInfo = userInfoService.getUser(username);
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (user == null) {
            session.setAttribute("user", userInfo);
            session.setMaxInactiveInterval(-1);
            user = (User) session.getAttribute("user");
        }
        List<String> menuNameList = menuSerivce.getMenuNameList(user.getGroupId());
        Map<String, Object> base = new HashMap<String, Object>();
        resultMap.put("code", 20000);
        String str = userInfo.getGroupId();
        String[] s = {str};
        base.put("userId",userInfo.getUserId());
        base.put("roles", s);
        base.put("introduction", "I am a super administrator");
        base.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        base.put("name", user.getAccount());
        base.put("username",user.getUsername());
        base.put("roleView", menuNameList);
        resultMap.put("data", base);
        return resultMap;
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout")
    @OperLog(operModul = "用户管理", operType = "8", operDesc = "登出")
    @ResponseBody
    public Map<String, Object> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        request.getSession().invalidate();
        Map<String, Object> reulst = new HashMap<String, Object>();
        reulst.put("code", 20000);
        reulst.put("data", "success");
        return reulst;
    }

    /**
     * 删除用户
     *
     * @return
     */
    @RequestMapping(value = "/deleteUser")
    @OperLog(operModul = "用户管理", operType = "4", operDesc = "删除用户")
    @ResponseBody
    public Map<String, Object> deleteUser(String id) {
        int count = userInfoService.deleteUser(id);
        Map<String, Object> reulst = new HashMap<String, Object>();
        Map<String, Object> result1 = new HashMap<String, Object>();
        if (count > 0) {
            result1.put("code", 20000);
            reulst.put("success", true);
        } else {
            result1.put("code", 20001);
            reulst.put("success", false);
        }
        result1.put("data", reulst);
        return result1;

    }


    /**
     * 查询用户管理列表
     * @param rows 行数
     * @param page 页数
     * @param type 状态
     * @return
     */
    @RequestMapping(value = "/getUserInfoList")
    @OperLog(operModul = "用户管理", operType = "1", operDesc = "查询用户管理列表")
    @ResponseBody
    public Map<String, Object> getUserInfoList(String username, Integer page, Integer rows, Integer type) {
        int start = page;
        int pageSize = rows;
        //查询系统用户列表
        List<User> pageList = userInfoService.queryList(start, pageSize, username, type);
        int count = userInfoService.queryListCount(username, type);
        //查询系统用户列表
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", 20000);
        result.put("data", pageList);
        result.put("total",count);
        return result;
    }

    /**
     * 批量删除用户
     *
     * @param ids 多个用户id
     * @return
     */
    @RequestMapping(value = "/deleteUsers")
    @OperLog(operModul = "用户管理", operType = "4", operDesc = "批量删除用户")
    @ResponseBody
    public Map<String, Object> deleteUsers(String ids) {
        int count = userInfoService.deleteUsers(ids);
        Map<String, Object> reulst = new HashMap<String, Object>();
        if (count > 0) {
            reulst.put("success", true);
            return reulst;
        }
        reulst.put("success", false);
        return reulst;
    }

    /**
     * 添加用户
     * @param user 用户对象
     * @return
     */
    @RequestMapping(value = "/addUser")
    @OperLog(operModul = "用户管理", operType = "2", operDesc = "新增用户")
    @ResponseBody
    public Map<String, Object> addUser(HttpServletRequest request, @RequestBody User user) {
        user.setUserId(StringUtils.getPrimarykeyId());
        user.setAccount(user.getAccount());
        user.setPassword(user.getPassword());
        user.setAddtime(new Date());
        //设置用户类型为系统用户
//        User sesion_user = (User) request.getSession().getAttribute("user");
        user.setUserType((short) 0);
//        user.setAdduser(sesion_user.getUserId());
        userInfoService.addUser(user);
        Map<String, Object> reulst = new HashMap<String, Object>();
        reulst.put("success", true);
        Map<String, Object> result1 = new HashMap<String, Object>();
        result1.put("code", 20000);
        result1.put("data", reulst);
        return result1;

    }

    /**
     * 验证注册时登录名是否重复
     */
    @RequestMapping(value = "/checkLoginName")
    @ResponseBody
    public Map<String, Object> checkLoginName(String userName) {
        int count = userInfoService.checkLoginName(userName);
        Map<String, Object> reulst = new HashMap<String, Object>();
        if (count > 0) {
            reulst.put("success", false);
        } else {
            reulst.put("success", true);
        }
        Map<String, Object> result1 = new HashMap<String, Object>();
        result1.put("code", 20000);
        result1.put("data", reulst);
        return result1;

    }

    /**
     * 获取用户信息
     * @param userId  用户id
     * @return
     */
    @RequestMapping(value = "/getUserInfoById")
    @OperLog(operModul = "用户管理", operType = "1", operDesc = "根据用户id获取用户信息")
    @ResponseBody
    public User getUserInfoById(String userId) {
        if (StringUtils.isEmpty(userId)) {
            throw new ServiceException("参数错误");
        }
        return userInfoService.getUserInfoBeanById(userId);
    }


    /**
     * 修改用户信息
     *
     * @param user 用户对象
     * @return
     */
    @RequestMapping(value = "/updateUserInfoBean")
    @OperLog(operModul = "用户管理", operType = "3", operDesc = "修改用户信息")
    @ResponseBody
    public Map<String, Object> updateUserInfoBean(@RequestBody User user) {
        int resultTemp = userInfoService.updateUserInfoBean(user);
        Map<String, Object> reulst = new HashMap<String, Object>();
        if (resultTemp > 0) {
            reulst.put("success", true);
        } else {
            reulst.put("success", false);

        }
        Map<String, Object> result1 = new HashMap<String, Object>();
        result1.put("code", 20000);
        result1.put("data", reulst);
        return result1;

    }

    /**
     * 得到session User信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getSessionUser")
    @OperLog(operModul = "用户管理", operType = "1", operDesc = "获取当前登录的用户信息")
    @ResponseBody
    public User getSessionUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        return (User) session.getAttribute("user");
    }

    /**
     * 改变用户状态
     *
     * @param userId 用户id
     * @param status 状态
     * @return
     */
    @RequestMapping(value = "/changeUserStatus")
    @OperLog(operModul = "用户管理", operType = "3", operDesc = "改变用户状态")
    @ResponseBody
    public Map<String, Object> changeUserStatus(String userId, String status) {
        int falg = userInfoService.changeUserStatus(userId, status);
        Map<String, Object> result = new HashMap<String, Object>();
        if (falg > 0) {
            result.put("success", true);
        } else {
            result.put("success", false);
        }
        Map<String, Object> result1 = new HashMap<String, Object>();
        result1.put("code", 20000);
        result1.put("data", result);
        return result1;

    }

    /**
     * 查询密码是否正确
     *
     * @param account 用户名
     * @param password 密码
     * @return
     */
    @RequestMapping(value = "/isPassword")
    @OperLog(operModul = "用户管理", operType = "1", operDesc = "查询密码是否正确")
    @ResponseBody
    public Map<String, Object> isPassword(String account, String password) {
        int falg = userInfoService.isPassword(account, password);
        Map<String, Object> result = new HashMap<String, Object>();
        if (falg > 0) {
            result.put("success", true);
        } else {
            result.put("success", false);
        }
        Map<String, Object> result1 = new HashMap<String, Object>();
        result1.put("code", 20000);
        result1.put("data", result);
        return result1;

    }

    /**
     *  修改密码
     * @param account 用户名
     * @param password 新密码
     * @param oldPassword 旧密码
     * @return
     */
    @RequestMapping(value = "/updatePassword")
    @OperLog(operModul = "用户管理", operType = "3", operDesc = "修改密码")
    @ResponseBody
    public Map<String, Object> updatePassword(String id, String password, String oldPassword) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (!StringUtils.isNullOrEmpty(oldPassword)) {
            if (userInfoService.isPassword(id, oldPassword) == 0) {
                result.put("success", false);
                Map<String, Object> result1 = new HashMap<String, Object>();
                result1.put("code", 20001);
                result.put("msg", "原始密码不正确，请重新输入！");
                result1.put("data", result);
                return result1;
            }
        }
        int falg = userInfoService.updatePassword(id, password);
        if (falg > 0) {
            result.put("success", true);
            Map<String, Object> result1 = new HashMap<String, Object>();
            result1.put("code", 20000);
            result.put("msg", "修改成功");
            result1.put("data", result);
            return result1;
        }else{
            result.put("success", false);
            Map<String, Object> result1 = new HashMap<String, Object>();
            result1.put("code", 20001);
            result.put("msg", "修改失败");
            result1.put("data", result);
            return result1;
        }

    }

    @RequestMapping(value = "/resetPassword")
    @OperLog(operModul = "用户管理", operType = "3", operDesc = "重置密码")
    @ResponseBody
    public Map<String, Object> resetPassword(String id, String password) {
        Map<String, Object> result = new HashMap<String, Object>();
        int falg = userInfoService.updatePassword(id, password);
        if (falg > 0) {
            result.put("success", true);
            Map<String, Object> result1 = new HashMap<String, Object>();
            result1.put("code", 20000);
            result.put("msg", "修改成功");
            result1.put("data", result);
            return result1;
        }else{
            result.put("success", false);
            Map<String, Object> result1 = new HashMap<String, Object>();
            result1.put("code", 20001);
            result.put("msg", "修改失败");
            result1.put("data", result);
            return result1;
        }

    }

}
